﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KimPhongCRM.Models;
using DevExpress.Web.Mvc;

namespace KimPhongCRM.Controllers
{
    [PermissionFilter]
    public class KhachHangController : BaseController
    {
        private Entities db = new Entities();
        List<KimPhongCRM.Models.sp_Select_Combobox_User_Result> listUser = new List<sp_Select_Combobox_User_Result>();
        public KhachHangController()
        {
            listUser = db.sp_Select_Combobox_User().ToList();
        }
        //
        // GET: /KhachHang/
        [MvcSiteMapProvider.MvcSiteMapNode(Title = "Khách Hàng", Key = "KhachHang", Clickable = true, ParentKey = "Home")]
        public ViewResult Index()
        {
            var UserList = db.Users.ToList();
            ViewData["listUser"] = listUser;
            return View();
        }

        public ViewResult Birthday()
        {
            var UserList = db.Users.ToList();
            ViewData["listUser"] = listUser;
            return View();
        }

        //
        // GET: /KhachHang/Details/5

        public ViewResult Details(long id)
        {
            tblKhachHang tblkhachhang = db.tblKhachHangs.Find(id);
            return View(tblkhachhang);
        }

        public ViewResult PopupDetail(long id)
        {
            tblKhachHang tblkhachhang = db.tblKhachHangs.Find(id);
            return View(tblkhachhang);
        }
        //
        // GET: /KhachHang/Create
        [MvcSiteMapProvider.MvcSiteMapNode(Title = "Tạo mới", Key = "CreateCustomer", Clickable = true, ParentKey = "KhachHang")]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /KhachHang/Create

        [HttpPost]
        public ActionResult Create(tblKhachHang tblkhachhang)
        {
            if (ModelState.IsValid)
            {
                db.tblKhachHangs.Add(tblkhachhang);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(tblkhachhang);
        }

        //
        // GET: /KhachHang/Edit/5
        [MvcSiteMapProvider.MvcSiteMapNode(Title = "Cập nhật", Key = "EditCustomer", Clickable = true, ParentKey = "KhachHang")]
        public ActionResult Edit(long id)
        {
            tblKhachHang tblkhachhang = db.tblKhachHangs.Find(id);
            return View(tblkhachhang);
        }

        //
        // POST: /KhachHang/Edit/5

        [HttpPost]
        public ActionResult Edit(tblKhachHang tblkhachhang)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tblkhachhang).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(tblkhachhang);
        }

        //
        // GET: /KhachHang/Delete/5

        public ActionResult Delete(long id)
        {
            tblKhachHang tblkhachhang = db.tblKhachHangs.Find(id);
            return View(tblkhachhang);
        }

        //
        // POST: /KhachHang/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(long id)
        {
            tblKhachHang tblkhachhang = db.tblKhachHangs.Find(id);
            db.tblKhachHangs.Remove(tblkhachhang);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        [ValidateInput(false)]
        public ActionResult GridViewKhachHangPartial()
        {
            var model = db.tblKhachHangs;
            ViewData["listUser"] = listUser;
            return PartialView("_GridViewKhachHangPartial", model.ToList());
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult GridViewKhachHangPartialAddNew(KimPhongCRM.Models.tblKhachHang item)
        {
            var model = db.tblKhachHangs;
            ViewData["listUser"] = listUser;
            if (ModelState.IsValid)
            {
                try
                {
                    model.Add(item);
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    ViewData["EditError"] = e.Message;
                }
            }
            else
                ViewData["EditError"] = "Please, correct all errors.";
            return PartialView("_GridViewKhachHangPartial", model.ToList());
        }
        [HttpPost, ValidateInput(false)]
        public ActionResult GridViewKhachHangPartialUpdate(KimPhongCRM.Models.tblKhachHang item)
        {
            var model = db.tblKhachHangs;
            ViewData["listUser"] = listUser;
            if (ModelState.IsValid)
            {
                try
                {
                    var modelItem = model.FirstOrDefault(it => it.maKH == item.maKH);
                    if (modelItem != null)
                    {
                        this.UpdateModel(modelItem);
                        db.SaveChanges();
                    }
                }
                catch (Exception e)
                {
                    ViewData["EditError"] = e.Message;
                }
            }
            else
                ViewData["EditError"] = "Please, correct all errors.";
            return PartialView("_GridViewKhachHangPartial", model.ToList());
        }
        [HttpPost, ValidateInput(false)]
        public ActionResult GridViewKhachHangPartialDelete(System.Int64 maKH)
        {
            var model = db.tblKhachHangs;
            ViewData["listUser"] = listUser;
            if (maKH != null)
            {
                try
                {
                    var item = model.FirstOrDefault(it => it.maKH == maKH);
                    if (item != null)
                        model.Remove(item);
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    ViewData["EditError"] = e.Message;
                }
            }
            return PartialView("_GridViewKhachHangPartial", model.ToList());
        }
        public ActionResult Report()
        {
            return View();
        }

        [ValidateInput(false)]
        public ActionResult listBirthdayPartial(long days)
        {
            var model = db.sp_Select_KhachHang_Birthday(days).ToList();
            return PartialView("_listBirthdayPartial", model);
        }
        /*====================== SEMD MAIL BIRTHDAY ===================================*/
        public ActionResult alertBirthday()
        {
            try
            {
                //Gửi thông báo khách hàng
                var eConfig = db.tblEmailConfigs.ToList().Where(c => c.isActive == true).First() as tblEmailConfig;
                //Lấy danh sách khách hàng có sinh nhật
                var dsSinhNhat = db.sp_Select_KhachHang_Birthday(eConfig.actionDay).ToList() as List<sp_Select_KhachHang_Birthday_Result>;
                //Kiểm tra giờ thực hiện
                DateTime now = DateTime.Now;
                if (eConfig.actionInTime.Value.Hour == now.Hour && Math.Abs(eConfig.actionInTime.Value.Minute - now.Minute) < 10)
                {
                    foreach (var value in dsSinhNhat)
                    {
                        if (value.alertBirthDay != 0)
                        {
                            var kh = db.tblKhachHangs.Find(value.maKH) as tblKhachHang;
                            if (kh.alertBirthDay > value.conlai || kh.alertBirthDay == -1)
                            {
                                string subject = "Thông báo sinh nhật";
                                string content = String.Format("Còn {0} ngày nữa là sinh nhật khách hàng {1} {2} - Mã:{3}", value.conlai, value.hoKH, value.tenKH, value.maKH);
                                db.sp_Update_arlertBirthDay(value.maKH, value.conlai);
                                Lib.NetUtils.SendEmail(subject, content, eConfig);
                            }
                        }
                    }
                }

                //Kiểm tra email và hủy gửi tin
                List<Dictionary<string, string>> email = Lib.NetUtils.reCeive(eConfig);
                if (email != null)
                {
                    foreach (var value in email)
                    {
                        string body = value["Content"].Trim().ToString();
                        body = body.ToLower();
                        if (body.IndexOf("huy") != -1)
                        {
                            string[] cmd = body.Split(' ');
                            if (cmd.Count() > 0)
                            {
                                int maKH = Convert.ToInt32(cmd[1]);
                                db.sp_Update_arlertBirthDay(maKH, 0);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ViewData["EditError"] = e.Message;
            }

            return null;
        }

        public ActionResult resetBirthday()
        {
            try
            {
                var eConfig = db.tblEmailConfigs.ToList().Where(c => c.isActive == true).First() as tblEmailConfig;
                //Lấy danh sách khách hàng đã ngừng thông báo cần reset
                var kh = db.tblKhachHangs.Where(k => k.alertBirthDay == 0 && (k.sinhNhatKH.Month <= DateTime.Now.Month&&k.sinhNhatKH.Day< DateTime.Now.Day)).ToList() as List<tblKhachHang>;
                foreach (var value in kh)
                {
                    db.sp_Update_arlertBirthDay(value.maKH, -1);
                }
            }
            catch (Exception e)
            {
                ViewData["EditError"] = e.Message;
            }

            return null;
        }
        /*====================== REPORT ===================================*/
        public ActionResult khReport()
        {
            return View();
        }
        public ActionResult ReportViewerPartial()
        {
            ViewData["rpKhachHang"] = new rpKhachHang();
            return PartialView("khReportPartial");
        }
        public ActionResult ExportReportViewer()
        {
            return DevExpress.Web.Mvc.ReportViewerExtension.ExportTo(new rpKhachHang());
        }
    }
}